import { useState } from 'react';
import { message } from 'antd';
import { getDocDetailsByDocId } from '@/views/DocList/pages/detail/api';
import { convertTiptapToDocx } from '@/utils/tiptapToDocxConverter';
import { convertTiptapToPdf, batchExportToPdf } from '@/utils/tiptapToPdfConverter';

// 导入所需的 Tiptap 扩展
import { Editor } from '@tiptap/core';
import { StarterKit } from '@tiptap/starter-kit';
import { Image } from '@tiptap/extension-image';
import { TaskItem } from '@tiptap/extension-task-item';
import { TaskList } from '@tiptap/extension-task-list';
import { TextAlign } from '@tiptap/extension-text-align';
import { Typography } from '@tiptap/extension-typography';
import { Highlight } from '@tiptap/extension-highlight';
import { Subscript } from '@tiptap/extension-subscript';
import { Superscript } from '@tiptap/extension-superscript';
import { Underline } from '@tiptap/extension-underline';
import { Color } from '@tiptap/extension-color';
import TextStyle from '@tiptap/extension-text-style';
import { Table } from '@tiptap/extension-table';
import { TableRow } from '@tiptap/extension-table-row';
import { TableCell } from '@tiptap/extension-table-cell';
import { TableHeader } from '@tiptap/extension-table-header';
import { Link } from '@tiptap/extension-link';

/**
 * 文档导出 Hook
 * 提供批量导出、单个导出等功能
 */
export const useDocExport = () => {
    const [exportLoading, setExportLoading] = useState(false);

    /**
     * 创建临时编辑器实例
     * @returns {Editor} 临时编辑器实例
     */
    const createTempEditor = () => {
        return new Editor({
            extensions: [
                StarterKit,
                TextAlign.configure({ types: ["heading", "paragraph"] }),
                Underline,
                TaskList,
                TaskItem.configure({ nested: true }),
                Highlight.configure({ multicolor: true }),
                Image,
                Typography,
                Superscript,
                Subscript,
                TextStyle,
                Color.configure({ types: [TextStyle.name] }),
                Table.configure({
                    resizable: true,
                }),
                TableRow,
                TableHeader,
                TableCell,
                Link.configure({ openOnClick: false }),
            ],
            editable: false, // 设置为不可编辑以提高性能
        });
    };

    /**
     * 批量导出选中的文档
     * @param {string[]} selectedDocs - 选中的文档ID数组
     * @returns {Promise<number>} 成功导出的文档数量
     */
    const handleBatchExport = async (selectedDocs) => {
        if (selectedDocs.length === 0) {
            message.warning('请先选择要导出的文档');
            return 0;
        }

        setExportLoading(true);
        try {
            // 获取选中文档的详细信息
            const exportPromises = selectedDocs.map(async (docId) => {
                try {
                    // 检查文档ID格式
                    if (!docId || typeof docId !== 'string') {
                        return null;
                    }
                    
                    const res = await getDocDetailsByDocId(docId);

                    if (res && res.code === 200 && res.data) {
                        const docData = res.data;

                        // 检查是否有内容
                        if (!docData.docContent) {
                            return {
                                docId: docData.docId,
                                docName: docData.docName,
                                content: null,
                                hasContent: false
                            };
                        }

                        // 解析文档内容
                        let parsedContent;
                        try {
                            parsedContent = typeof docData.docContent === 'string'
                                ? JSON.parse(docData.docContent)
                                : docData.docContent;
                        } catch (parseError) {
                            message.error(`文档 ${docData.docName} 内容格式错误`);
                            return {
                                docId: docData.docId,
                                docName: docData.docName,
                                content: null,
                                hasContent: false
                            };
                        }

                        return {
                            docId: docData.docId,
                            docName: docData.docName,
                            content: parsedContent,
                            hasContent: true
                        };
                    } else {
                        message.error(`获取文档 ${docId} 详情失败: ${res?.msg || '响应格式错误'}`);
                        return null;
                    }
                } catch (error) {
                    // 检查是否是 "No value present" 错误
                    if (error.message && error.message.includes('No value present')) {
                        message.error(`文档 ${docId} 不存在或已被删除`);
                    } else {
                        message.error(`获取文档 ${docId} 详情失败: ${error.message}`);
                    }
                    return null;
                }
            });
            
            const docDetails = await Promise.all(exportPromises);
            const validDocs = docDetails.filter(doc => doc !== null);
            const docsWithContent = validDocs.filter(doc => doc.hasContent);

            if (validDocs.length === 0) {
                message.error('没有可导出的文档');
                return 0;
            }

            if (docsWithContent.length === 0) {
                message.warning('选中的文档都没有内容，无法导出');
                return 0;
            }

            // 逐个导出文档
            let successCount = 0;
            for (const doc of docsWithContent) {
                try {
                    await convertTiptapToDocx(doc.content, doc.docName);
                    successCount++;
                } catch (error) {
                    message.error(`导出文档 "${doc.docName}" 失败: ${error.message}`);
                }
            }

            // 只在有成功导出的文档时显示成功消息
            if (successCount > 0) {
                message.success(`成功导出 ${successCount} 个文档`);
            }

            return successCount;
        } catch (error) {
            message.error('批量导出失败');
            throw error;
        } finally {
            setExportLoading(false);
        }
    };

    /**
     * 导出单个文档
     * @param {string} docId - 文档ID
     * @param {string} docName - 文档名称（可选）
     * @returns {Promise<boolean>} 是否导出成功
     */
    const exportSingleDoc = async (docId, docName) => {
        setExportLoading(true);
        try {
            const res = await getDocDetailsByDocId(docId);
            
            if (res && res.code === 200 && res.data && res.data.docContent) {
                let parsedContent;
                try {
                    parsedContent = typeof res.data.docContent === 'string'
                        ? JSON.parse(res.data.docContent)
                        : res.data.docContent;
                } catch (parseError) {
                    throw new Error('文档内容格式错误');
                }

                await convertTiptapToDocx(parsedContent, docName || res.data.docName);
                // 移除这里的成功消息，由调用方处理
                return true;
            } else {
                message.error('文档不存在或没有内容');
                return false;
            }
        } catch (error) {
            message.error(`导出失败: ${error.message}`);
            return false;
        } finally {
            setExportLoading(false);
        }
    };

    /**
     * 导出多个文档（批量）
     * @param {Array} docs - 文档数组，每个文档包含 content 和 name 属性
     * @returns {Promise<number>} 成功导出的文档数量
     */
    const exportMultipleDocs = async (docs) => {
        setExportLoading(true);
        try {
            let successCount = 0;
            for (let i = 0; i < docs.length; i++) {
                const doc = docs[i];
                try {
                    await convertTiptapToDocx(doc.content, `${doc.name}_${i + 1}`);
                    successCount++;
                    // 添加延迟避免浏览器阻止多个下载
                    await new Promise(resolve => setTimeout(resolve, 500));
                } catch (error) {
                    console.error(`导出文档 ${doc.name} 失败:`, error);
                }
            }
            
            if (successCount > 0) {
                message.success(`成功导出 ${successCount} 个文档`);
            }
            return successCount;
        } catch (error) {
            message.error('批量导出失败');
            throw error;
        } finally {
            setExportLoading(false);
        }
    };

    /**
     * 批量导出选中的文档为PDF
     * @param {string[]} selectedDocs - 选中的文档ID数组
     * @returns {Promise<number>} 成功导出的文档数量
     */
    const handleBatchExportToPdf = async (selectedDocs) => {
        if (selectedDocs.length === 0) {
            message.warning('请先选择要导出的文档');
            return 0;
        }

        setExportLoading(true);
        try {
            // 获取选中文档的详细信息
            const exportPromises = selectedDocs.map(async (docId) => {
                try {
                    const res = await getDocDetailsByDocId(docId);

                    if (res && res.code === 200 && res.data) {
                        const docData = res.data;

                        // 检查是否有内容
                        if (!docData.docContent) {
                            return {
                                docId: docData.docId,
                                docName: docData.docName,
                                content: null,
                                hasContent: false
                            };
                        }

                        // 解析文档内容
                        let parsedContent;
                        try {
                            parsedContent = typeof docData.docContent === 'string'
                                ? JSON.parse(docData.docContent)
                                : docData.docContent;
                        } catch (parseError) {
                            message.error(`文档 ${docData.docName} 内容格式错误`);
                            return {
                                docId: docData.docId,
                                docName: docData.docName,
                                content: null,
                                hasContent: false
                            };
                        }

                        return {
                            docId: docData.docId,
                            docName: docData.docName,
                            content: parsedContent,
                            hasContent: true
                        };
                    } else {
                        message.error(`获取文档 ${docId} 详情失败: ${res?.msg || '响应格式错误'}`);
                        return null;
                    }
                } catch (error) {
                    message.error(`获取文档 ${docId} 详情失败: ${error.message}`);
                    return null;
                }
            });
            
            const docDetails = await Promise.all(exportPromises);
            const validDocs = docDetails.filter(doc => doc !== null);
            const docsWithContent = validDocs.filter(doc => doc.hasContent);

            if (validDocs.length === 0) {
                message.error('没有可导出的文档');
                return 0;
            }

            if (docsWithContent.length === 0) {
                message.warning('选中的文档都没有内容，无法导出');
                return 0;
            }

            // 逐个导出PDF文档
            let successCount = 0;
            for (const doc of docsWithContent) {
                try {
                    // 创建一个临时的编辑器实例来生成HTML
                    const tempEditor = createTempEditor();
                    tempEditor.commands.setContent(doc.content);
                    const html = tempEditor.getHTML();
                    tempEditor.destroy();

                    await convertTiptapToPdf(html, doc.docName);
                    successCount++;
                    // 添加延迟避免浏览器阻止多个下载
                    await new Promise(resolve => setTimeout(resolve, 1000));
                } catch (error) {
                    message.error(`导出PDF文档 "${doc.docName}" 失败: ${error.message}`);
                }
            }

            // 只在有成功导出的文档时显示成功消息
            if (successCount > 0) {
                message.success(`成功导出 ${successCount} 个PDF文档`);
            }

            return successCount;
        } catch (error) {
            message.error('批量导出PDF失败');
            throw error;
        } finally {
            setExportLoading(false);
        }
    };

    /**
     * 导出单个文档为PDF
     * @param {string} docId - 文档ID
     * @param {string} docName - 文档名称（可选）
     * @returns {Promise<boolean>} 是否导出成功
     */
    const exportSingleDocToPdf = async (docId, docName) => {
        setExportLoading(true);
        try {
            const res = await getDocDetailsByDocId(docId);
            
            if (res && res.code === 200 && res.data && res.data.docContent) {
                let parsedContent;
                try {
                    parsedContent = typeof res.data.docContent === 'string'
                        ? JSON.parse(res.data.docContent)
                        : res.data.docContent;
                } catch (parseError) {
                    throw new Error('文档内容格式错误');
                }

                // 创建一个临时的编辑器实例来生成HTML
                const tempEditor = createTempEditor();
                tempEditor.commands.setContent(parsedContent);
                const html = tempEditor.getHTML();
                tempEditor.destroy();

                await convertTiptapToPdf(html, docName || res.data.docName);
                return true;
            } else {
                message.error('文档不存在或没有内容');
                return false;
            }
        } catch (error) {
            message.error(`PDF导出失败: ${error.message}`);
            return false;
        } finally {
            setExportLoading(false);
        }
    };

    return {
        exportLoading,
        handleBatchExport,
        exportSingleDoc,
        exportMultipleDocs,
        handleBatchExportToPdf,  // 新增PDF导出
        exportSingleDocToPdf,    // 新增单个PDF导出
    };
};